package com.tomato.controller;

import com.tomato.dto.LoginDTO;
import com.tomato.dto.RegisterDTO;
import com.tomato.dto.Result;
import com.tomato.service.UserService;
import com.tomato.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "用户认证", description = "用户登录、注册、注销等接口")
public class AuthController {
    private final UserService userService;
    private final JwtUtil jwtUtil; // 注入JwtUtil

    public AuthController(UserService userService, JwtUtil jwtUtil) {
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO) {
        log.debug("Login request for phone: {}", loginDTO.getPhone());
        String token = userService.login(loginDTO);
        return Result.success(token);
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Long> register(@RequestBody RegisterDTO registerDTO) {
        log.debug("Register request for phone: {}", registerDTO.getPhone());
        Long userId = userService.register(registerDTO);
        return Result.success(userId);
    }

    @Operation(summary = "用户永久注销")
    @DeleteMapping("/logout")
    public Result<Void> logout(@RequestHeader("Authorization") String token) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        log.debug("Logout request for user: {}", userId);
        userService.deleteUser(userId);
        return Result.success();
    }
}